class Solution {
public:
    int minFallingPathSum(vector<vector<int>>& matrix) {
        int n = matrix.size(), m = matrix[0].size();
        vector<vector<int>> dp(n, vector<int>(m + 2, INT_MAX));
        for (int j = 0; j < m; j++) {
            dp[0][j + 1] = matrix[0][j];
        }

        for (int i = 1; i < n; i++) {
            for (int j = 1; j < m; j++) {
                dp[i][j] =
                    min(min(dp[i - 1][j - 1], dp[i - 1][j]), dp[i - 1][j + 1]) +
                    matrix[i][j - 1];
            }
        }

        int ret = INT_MAX;
        for (int j = 1; j <= m; j++) {
            ret = min(ret, dp[n - 1][j]);
        }
        return ret;
    }
};